package com.example.slider.validate.controller;

import com.example.slider.validate.model.CheckImgValidateModel;
import com.example.slider.validate.util.VerifyImageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
public class ImageValidateController {
    @GetMapping("/imageValidate")
    public String imageValidate() {
        return "imageValidate";
    }

    @ResponseBody
    @PostMapping("/common/createImgValidate")
    public Map<String, Object> createImgValidate() throws Exception {
        Random random = new Random();
        File targetFile = new File(this.getClass().getResource("/static/target/" + (random.nextInt(20) + 1) + ".jpg").getPath());
        File templateFile = new File(this.getClass().getResource("/static/template/" + (random.nextInt(4) + 1) + ".png").getPath());
        Map<String, byte[]> pictureMap = VerifyImageUtil.pictureTemplatesCut(templateFile, targetFile, "png", "jpg");
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("oriCopyImage", Base64Utils.encodeToString((byte[]) pictureMap.get("oriCopyImage")));
        dataMap.put("newImage", Base64Utils.encodeToString((byte[]) pictureMap.get("newImage")));

        Map<String, Object> data = new HashMap<>();
        data.put("data", dataMap);
        data.put("status", 200);
        return data;
    }

    /**
     * TODO 校验位置数据
     *
     * @param checkImgValidateModel
     * @return
     */
    @ResponseBody
    @PostMapping("/common/checkImgValidate")
    public Map<String, Object> checkImgValidate(CheckImgValidateModel checkImgValidateModel) {
        Map<String, Object> data = new HashMap<>();
        data.put("info", "校验位置失败");
        data.put("status", 500);
        return data;
    }
}
